package com.cochain.dynamicdatasource;

import com.cochain.dynamicdatasource.entity.po.DataSource;
import com.cochain.dynamicdatasource.mapper.DataSourceMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DBChangeServiceImpl implements DBChangeService {

    private DataSourceMapper dataSourceMapper;

    private DynamicDataSource dynamicDataSource;

    public DBChangeServiceImpl(DataSourceMapper dataSourceMapper,
                               DynamicDataSource dynamicDataSource){

        this.dataSourceMapper = dataSourceMapper;
        this.dynamicDataSource = dynamicDataSource;

    }

    @Override
    public List<DataSource> get() { return dataSourceMapper.get(); }

    @Override
    public boolean changeDb(String datasourceId) throws Exception {

        //默认切换到主数据源，进行整体资源的查找
        DBContextHolder.clearDataSource();
        List<DataSource> dataSourceList = dataSourceMapper.get();
        for(DataSource source : dataSourceList){
            if(source.getDatasourceId().equals(datasourceId)){
                System.out.println("需要使用的数据源已经找到，datasourceId是："+source.getDatasourceId());
                //创建数据源连接&检查，若存在则不需要重新创建
                dynamicDataSource.createDataSourceWithCheck(source);
                //切换到该数据源
                DBContextHolder.setDataSource(source.getDatasourceId());
                return true;
            }
        }
        return false;

    }

}
